import React from 'react';
import { Modal, Form, Input, DatePicker, Select } from 'antd';
import { BaseForm } from '../Form/BaseForm';
import type { BorrowRecord, CreateBorrowRequest } from '../../../store/slices/borrowSlice';
import { useMember } from '../../../hooks/useMember'; // 根据实际路径调整
import { useMaterial } from '../../../hooks/useMaterial'; // 根据实际路径调整
import dayjs from 'dayjs';

const { Option } = Select;
const { TextArea } = Input;

interface BorrowFormValues {
  userId: number;
  materialId: number;
  expectedReturn: string;
  purpose: string;
}

interface BorrowModalProps {
  visible: boolean;
  editingBorrow: BorrowRecord | null;
  onSubmit: (values: BorrowFormValues) => Promise<void>;
  onCancel: () => void;
  loading?: boolean;
}

export const BorrowModal: React.FC<BorrowModalProps> = ({
  visible,
  editingBorrow,
  onSubmit,
  onCancel,
  loading = false,
}) => {
  const [form] = Form.useForm();

  // 使用实际的 hooks 获取成员和物资数据
  const { members, initMembers } = useMember();
  const { materials, getMaterials } = useMaterial();

  // 初始化数据
  React.useEffect(() => {
    if (visible) {
      // 获取成员和物资列表
      initMembers();
      getMaterials();

      if (editingBorrow) {
        form.setFieldsValue({
          userId: editingBorrow.userId,
          materialId: editingBorrow.materialId,
          expectedReturn: dayjs(editingBorrow.expectedReturn),
          purpose: editingBorrow.purpose,
        });
      } else {
        form.resetFields();
        // 设置默认的预计归还日期为7天后
        form.setFieldsValue({
          expectedReturn: dayjs().add(7, 'day'),
        });
      }
    }
  }, [visible, editingBorrow, form, initMembers, getMaterials]);

  // 过滤可用的物资（状态为 available 的物资）
  const availableMaterials = materials.filter(material =>
    material.status === 'available'
  );

  const handleSubmit = async (values: BorrowFormValues) => {
    try {
      const submitValues = {
        ...values,
        expectedReturn: values.expectedReturn,
      };
      await onSubmit(submitValues);
      form.resetFields();
    } catch (error) {
      throw error;
    }
  };

  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };

  return (
    <Modal
      title={editingBorrow ? '编辑借用记录' : '新增借用记录'}
      open={visible}
      onCancel={handleCancel}
      footer={null}
      width={600}
    >
      <BaseForm
        form={form}
        onFinish={handleSubmit}
        onCancel={handleCancel}
        submitText={editingBorrow ? '更新' : '创建'}
        cancelText="取消"
        layout="vertical"
        loading={loading}
      >
        <Form.Item
          label="借用人"
          name="userId"
          rules={[{ required: true, message: '请选择借用人' }]}
        >
          <Select placeholder="请选择借用人" loading={!members}>
            {members.map(user => (
              <Option key={user.id} value={user.id}>
                {user.name} ({user.department})
              </Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          label="借用物资"
          name="materialId"
          rules={[{ required: true, message: '请选择借用物资' }]}
        >
          <Select placeholder="请选择借用物资" loading={!materials}>
            {availableMaterials.map(material => (
              <Option key={material.id} value={material.id}>
                {material.name} - {material.location}
                {material.status === 'available' && (
                  <span style={{ color: '#52c41a' }}> (可用)</span>
                )}
              </Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          label="预计归还日期"
          name="expectedReturn"
          rules={[{ required: true, message: '请选择预计归还日期' }]}
        >
          <DatePicker
            style={{ width: '100%' }}
            disabledDate={(current) => {
              return current && current < dayjs().startOf('day');
            }}
          />
        </Form.Item>

        <Form.Item
          label="借用用途"
          name="purpose"
          rules={[
            { required: true, message: '请输入借用用途' },
            { min: 5, max: 200, message: '借用用途长度为5-200个字符' }
          ]}
        >
          <TextArea
            placeholder="请输入借用用途"
            rows={3}
          />
        </Form.Item>
      </BaseForm>
    </Modal>
  );
};